package com.ruoyi.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.domain.*;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mapper.PointsMapper;
import com.ruoyi.service.IPointsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 积分Service业务层处理
 * 
 * @author fst
 * @date 2025-04-14
 */
@Service
public class PointsServiceImpl implements IPointsService 
{
    @Autowired
    private PointsMapper pointsMapper;

    /**
     * 查询积分
     * 
     * @param id 积分主键
     * @return 积分
     */
    @Override
    public Points selectPointsById(Long id)
    {
        return pointsMapper.selectPointsById(id);
    }

    /**
     * 查询积分列表
     * 
     * @param points 积分
     * @return 积分
     */
    @Override
    public List<Points> selectPointsList(Points points)
    {
        return pointsMapper.selectPointsList(points);
    }

    /**
     * 新增积分
     * 
     * @param points 积分
     * @return 结果
     */
    @Override
    public int insertPoints(Points points)
    {
        return pointsMapper.insertPoints(points);
    }

    /**
     * 修改积分
     * 
     * @param points 积分
     * @return 结果
     */
    @Override
    public int updatePoints(Points points)
    {
        return pointsMapper.updatePoints(points);
    }

    /**
     * 批量删除积分
     * 
     * @param ids 需要删除的积分主键
     * @return 结果
     */
    @Override
    public int deletePointsByIds(Long[] ids)
    {
        return pointsMapper.deletePointsByIds(ids);
    }

    /**
     * 删除积分信息
     * 
     * @param id 积分主键
     * @return 结果
     */
    @Override
    public int deletePointsById(Long id)
    {
        return pointsMapper.deletePointsById(id);
    }

    @Override
    public PointVo getPointsByUserId(Long userId) {
        PointsDTO pointsByUserId = pointsMapper.getPointsByUserId(userId);
        UserVO user = pointsMapper.getUserName(userId);
        String userName = pointsMapper.getName(userId);
        PointVo pointVo = new PointVo();
        if(pointsByUserId != null){
            pointVo.setPoints(pointsByUserId.getPoints());
            pointVo.setId(pointsByUserId.getId());
        }else{
            pointVo.setPoints(0L);
            pointVo.setId(userId);
        }
        pointVo.setUserName(userName);
        pointVo.setAvatar(user.getAvatar());
        pointVo.setEmail(user.getEmail());
        pointVo.setPhoneNumber(user.getPhoneNumber());
        return pointVo;
    }

    @Override
    @Transactional
    public Object subscribe(SubscribeDTO subscribeDTO) {
        // 扣减积分
        Long userId = subscribeDTO.getUserId();
        Long points = pointsMapper.selectPointsByUserId(userId);
        if(userId == null || (points - subscribeDTO.getPoints()) < 0){
            return "积分不足，请充值后再试。";
        }
        Long changePoints = points - subscribeDTO.getPoints();
        // 更新积分
        int isSuc = pointsMapper.updatePointsByUserId(changePoints, userId);
        if(isSuc == 0){
            return "扣减积分失败，请重试。";
        }
        List<Subscribe> subscribeList = new ArrayList<>();

        // 新增订阅
        Long novelId = pointsMapper.selectNovelId(subscribeDTO.getNovelName());
        for (String orderNum : subscribeDTO.getOrderNum()) {
            Subscribe subscribe = new Subscribe();

            Long chapterId = pointsMapper.selectChapterId(orderNum, novelId);
            Long point = 10L;
            String novelName = subscribeDTO.getNovelName();
            subscribe.setId(chapterId);
            subscribe.setUserId(userId);
            subscribe.setPoints(point);
            subscribe.setNovelName(novelName);
            subscribe.setNovelId(novelId);
            subscribe.setCreateTime(new Date());
            subscribeList.add(subscribe);
        }
        int isScu2 = pointsMapper.insertPointsMany(subscribeList);
        if(isScu2 == 0){
            return "订阅失败，请重试。";
        }

        // 新增order表
        Order order = new Order();
        order.setUserId(userId);
        order.setPoints(subscribeDTO.getPoints());
        order.setOriginalPoints(points);
        order.setCurrentPoints(changePoints);
        order.setNovelId(novelId);
        order.setNovelName(subscribeDTO.getNovelName());
        order.setOrderNo(subscribeDTO.getOrderNum().toString());
        order.setType("0");
        order.setCreateTime(new Date());
        int isSuc3 = pointsMapper.insertOrder(order);
        if(isSuc3 == 0){
            return "写入订单失败，请重试。";
        }
        // 更新小说订阅积分
        int isSuc4 = pointsMapper.updateNovelPoints(novelId, subscribeDTO.getPoints());
        if(isSuc4 == 0){
            return "更新小说订阅积分失败，请重试。";
        }
        return "订阅成功";
    }

    @Override
    public List<Directory> getSubscribeList(Long userId, String title) {
        // 先查询小说id，然后查询章节表中的所有需要订阅的章节id
        Long novelId = pointsMapper.selectNovelId(title);
        List<Long> subscribeList = pointsMapper.selectChapterIds(novelId);

        // 查询所有订阅的章节id
        List<Subscribe> subscribeListByUserId = pointsMapper.selectSubscribeListByUserId(userId, novelId);

        // 如果订阅了，则将订阅的章节id从subscribeList中移除
        for (Subscribe subscribe : subscribeListByUserId) {
            subscribeList.remove(subscribe.getId());
        }

        // 现在剩下的就是，还未订阅的章节id  subscribeList
        List<Directory> directoryArrayList = new ArrayList<>();
        for(Long id : subscribeList){
            Directory  directories =pointsMapper.selectChapterList(id);
            directoryArrayList.add(directories);
        }


        return directoryArrayList;
    }

    @Override
    @Transactional
    public Object pass(OrdersDTO ordersDTO) {
        // 查询该用户积分是否足够支付
        Long userId = ordersDTO.getUserId();
        Long points = pointsMapper.selectPointsByUserId(userId);
        if(userId == null || (points - ordersDTO.getPoints()) < 0){
            return "积分不足，请充值后再试。";
        }
        Long changePoints = points - ordersDTO.getPoints();
        // 更新积分
        int isSuc = pointsMapper.updatePointsByUserId(changePoints, userId);
        if(isSuc == 0){
            return "扣减积分失败，请重试。";
        }
        // 增加小说表中的月票
        Long novelId = pointsMapper.selectNovelId(ordersDTO.getNovelName());
        int isSuc1 = pointsMapper.updateNovelPass(ordersDTO.getPass(), novelId);
        if(isSuc1 == 0){
            return "增加月票失败，请重试。";
        }

        // 增加order表
        Order order = new Order();
        order.setUserId(userId);
        order.setPoints(ordersDTO.getPoints());
        order.setOriginalPoints(points);
        order.setCurrentPoints(changePoints);
        order.setNovelName(ordersDTO.getNovelName());
        order.setNovelId(novelId);
        order.setOrderNo("");
        order.setType("2"); // 月票
        order.setCreateTime(new Date());
        int isSuc2 = pointsMapper.insertOrder(order);
        if(isSuc2 == 0){
            return "写入订单失败，请重试。";
        }
        return "购买成功";
    }

    @Override
    public AuthorPoints calculatePoints(Long userId) {
        // 查询所有小说的订阅积分
        List<Long> tippingList = pointsMapper.selectNovelTippingList(userId);

        // 查询所有小说月票数
        List<Long> passList = pointsMapper.selectNovelPassList(userId);

        //计算订阅总积分
        Long subscribePoints = 0L;
        for (Long points : tippingList) {
            subscribePoints += points;
        }

        //计算总月票数
        Long totalPass = 0L;
        for (Long pass : passList) {
            totalPass += pass;
        }
        // 计算月票积分
        Long passPoints = totalPass * 10L;

        //计算总积分
        Long totalPoints = subscribePoints + passPoints;

        AuthorPoints authorPoints = new AuthorPoints();
        authorPoints.setTipping(subscribePoints);
        authorPoints.setPass(totalPass);
        authorPoints.setPassPoints(passPoints);
        authorPoints.setTotalPoints(totalPoints);
        return authorPoints;
    }
}
